using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MVCWeekOne.Models;
using System.Text.Json;
using B.S.XZYData.Domain.LJC.Dto;
using ErrorCode = B.S.XZYData.ErrorCode;

namespace MVCWeekOne.Controllers
{
    /// <summary>
    /// 工单报工关联管理控制器
    /// </summary>
    public class WorkOrderReportController : Controller
    {
        private readonly HttpClient _httpClient;
        private readonly ApiSettings _apiSettings;

        public WorkOrderReportController(IHttpClientFactory httpClientFactory, IOptions<ApiSettings> apiSettings)
        {
            _httpClient = httpClientFactory.CreateClient();
            _apiSettings = apiSettings.Value;
            
            // 配置HttpClient超时
            _httpClient.Timeout = TimeSpan.FromSeconds(_apiSettings.TimeoutSeconds);
        }

        /// <summary>
        /// 工单报工关联列表页面
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Index()
        {
            var workOrderReports = new List<WorkOrderReportViewDto>();

            try
            {
                // 调用API获取工单报工关联列表
                var response = await _httpClient.GetAsync($"{_apiSettings.ReadApiUrl}/WorkOrderReport/list?index=1&size=50");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiPageing<WorkOrderReportViewDto>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.Code == (int)ErrorCode.ApiEnum.Success)
                    {
                        workOrderReports = apiResult.PageData?.ToList() ?? new List<WorkOrderReportViewDto>();
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                ViewBag.Error = $"获取工单报工关联列表失败：{ex.Message}";
            }

            return View(workOrderReports);
        }

        /// <summary>
        /// 获取工单报工关联列表（AJAX调用）
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">每页大小</param>
        /// <param name="workOrderCode">工单编号</param>
        /// <param name="productCode">产品编号</param>
        /// <param name="productName">产品名称</param>
        /// <param name="status">状态</param>
        /// <param name="createBy">创建人</param>
        /// <param name="createStartDate">创建开始日期</param>
        /// <param name="createEndDate">创建结束日期</param>
        /// <param name="sortField">排序字段</param>
        /// <param name="sortOrder">排序方向</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetWorkOrderReportList(
            int index = 1,
            int size = 20,
            string? workOrderCode = null,
            string? productCode = null,
            string? productName = null,
            string? status = null,
            string? createBy = null,
            DateTime? createStartDate = null,
            DateTime? createEndDate = null,
            string? sortField = "CreateTime",
            string? sortOrder = "desc")
        {
            try
            {
                // 构建查询参数
                var queryParams = new List<string>
                {
                    $"index={index}",
                    $"size={size}"
                };

                if (!string.IsNullOrEmpty(workOrderCode))
                    queryParams.Add($"workOrderCode={Uri.EscapeDataString(workOrderCode)}");
                
                if (!string.IsNullOrEmpty(productCode))
                    queryParams.Add($"productCode={Uri.EscapeDataString(productCode)}");
                
                if (!string.IsNullOrEmpty(productName))
                    queryParams.Add($"productName={Uri.EscapeDataString(productName)}");
                
                if (!string.IsNullOrEmpty(status))
                    queryParams.Add($"status={status}");
                
                if (!string.IsNullOrEmpty(createBy))
                    queryParams.Add($"createBy={Uri.EscapeDataString(createBy)}");
                
                if (createStartDate.HasValue)
                    queryParams.Add($"createStartDate={createStartDate.Value:yyyy-MM-dd}");
                
                if (createEndDate.HasValue)
                    queryParams.Add($"createEndDate={createEndDate.Value:yyyy-MM-dd}");
                
                if (!string.IsNullOrEmpty(sortField))
                    queryParams.Add($"sortField={sortField}");
                
                if (!string.IsNullOrEmpty(sortOrder))
                    queryParams.Add($"sortOrder={sortOrder}");

                var queryString = string.Join("&", queryParams);
                
                // 调用API获取数据
                var response = await _httpClient.GetAsync($"{_apiSettings.ReadApiUrl}/WorkOrderReport/list?{queryString}");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiPageing<WorkOrderReportViewDto>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.Code == (int)ErrorCode.ApiEnum.Success)
                    {
                        return Json(new { success = true, data = apiResult });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "获取数据失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"API调用失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取工单报工关联列表失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取统计信息（AJAX调用）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetStatistics()
        {
            try
            {
                // 调用API获取统计信息
                var response = await _httpClient.GetAsync($"{_apiSettings.ReadApiUrl}/WorkOrderReport/statistics");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<ApiResult<object>>(jsonContent, new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    if (apiResult != null && apiResult.Code == (int)ErrorCode.ApiEnum.Success)
                    {
                        return Json(new { success = true, data = apiResult.Data });
                    }
                    else
                    {
                        return Json(new { success = false, message = apiResult?.Msg ?? "获取统计信息失败" });
                    }
                }
                else
                {
                    return Json(new { success = false, message = $"API调用失败：{response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取统计信息失败：{ex.Message}" });
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _httpClient?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
